//
// Created by icbc on 22-9-19.
//
#include "debug.h"
#include <RollingFileAppender.h>
#include <ConsoleAppender.h>
#include <QDir>
#include <QStandardPaths>
#include <QCoreApplication>

#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
Q_LOGGING_CATEGORY(KRFB_FB_PIPEWIRE, "krfb.framebuffer.pipewire", QtInfoMsg)
Q_LOGGING_CATEGORY(KRFB, "krfb.krfb", QtInfoMsg)
Q_LOGGING_CATEGORY(XdgDesktopPortalKdeRemoteDesktop, "krfb.xdp", QtInfoMsg)
Q_LOGGING_CATEGORY(XdgDesktopPortalKdeWaylandIntegration, "xdp-kde-wayland-integration")
#else
Q_LOGGING_CATEGORY(KRFB, "krfb.krfb")
Q_LOGGING_CATEGORY(XdgDesktopPortalKdeRemoteDesktop, "krfb.xdp")
Q_LOGGING_CATEGORY(KRFB_FB_PIPEWIRE, "krfb.framebuffer.pipewire")
#endif

LogUtil::LogUtil()
{
}

void LogUtil::registerLogger(const char *logpath)
{
    QString logPath;
    if (logpath == NULL) {
        QString cachePath = QStandardPaths::standardLocations(QStandardPaths::CacheLocation).at(0);
        if (!QDir(cachePath).exists()) {
            QDir(cachePath).mkpath(cachePath);
        }
        logPath = QString("%1%2%3.log").arg(cachePath).arg(QDir::separator()).arg(qApp->applicationName());
    } else {
        logPath = logpath;
    }
    //    QString m_format = "%{time}{yyyy-MM-dd, HH:mm:ss.zzz} [%{type:-7}] [%{file:-20} %{function:-35} %{line}] %{message}\n";
    QString m_format = "%{time}{yyyy-MM-dd, HH:mm:ss.zzz} [%{type:-7}] [%{file} %{function} %{line}] %{message}\n";

    auto rollingFileAppender = new Dtk::Core::RollingFileAppender(logPath);
    rollingFileAppender->setFormat(m_format);
    rollingFileAppender->setLogFilesLimit(5);
    rollingFileAppender->setDatePattern(Dtk::Core::RollingFileAppender::DailyRollover);
    Dtk::Core::logger->registerAppender(rollingFileAppender);
    Dtk::Core::logger->registerCategoryAppender("krfb.krfb", rollingFileAppender);
    Dtk::Core::logger->registerCategoryAppender("krfb.framebuffer.pipewire", rollingFileAppender);
    Dtk::Core::logger->registerCategoryAppender("krfb.xdp", rollingFileAppender);
    Dtk::Core::logger->registerCategoryAppender("xdp-kde-wayland-integration", rollingFileAppender);

    auto consoleAppender = new Dtk::Core::ConsoleAppender;
    consoleAppender->setFormat(m_format);
    Dtk::Core::logger->registerAppender(consoleAppender);
    Dtk::Core::logger->registerCategoryAppender("krfb.krfb", consoleAppender);
    Dtk::Core::logger->registerCategoryAppender("krfb.framebuffer.pipewire", consoleAppender);
    Dtk::Core::logger->registerCategoryAppender("krfb.xdp", consoleAppender);
    Dtk::Core::logger->registerCategoryAppender("xdp-kde-wayland-integration", consoleAppender);
}
